package com.practice.concurrency;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CompletionServiceMain {

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		CompletionService<String> completion = new ExecutorCompletionService<String>(
				service);
		for (int i = 0; i < 10; i++) {
			completion.submit(new CompletionServiceCommand(i));
		}
		for (int i = 0; i < 10; i++) {
			try {
				Future<String> future = completion.take();
				System.out.println(future.get());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		service.shutdown();
	}
}

class CompletionServiceCommand implements Callable<String> {
	private int id;

	public CompletionServiceCommand(int id) {
		this.id = id;
	}
	
	public String call() throws Exception {
		int time = (int) (Math.random() * 1000);
		try {
			System.out.println(this.id + " start");
			Thread.sleep(time);
			System.out.println(this.id + " end");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return this.id + ": " + time;
	}
}
